package servlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import javabean.Factory;
import javabean.book.Book;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

public class BookEditServlet extends BaseServlet{

	private ServletConfig config;
    //初始化Servlet
    final public void init(ServletConfig config)
                throws ServletException{
    this.config=config;
    }
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -4194629595765316697L;

	@Override
	protected void service() throws Exception {
		boolean tag = false;
		//获取传过来的信息
		String path = request.getSession().getServletContext().getRealPath("/img/upload");	//临时路径
		String path1 = request.getSession().getServletContext().getRealPath("/img/book");	//存放路径
		String isbn = request.getParameter("isbn") ;
		String uid = (String) getSession().getAttribute("uid") ;
		String bid = request.getParameter("bid");
		if(uid!=null){
			if(isbn!=null && !"".equals(isbn)){
				String bname = request.getParameter("bname") ;
				String author = request.getParameter("author") ;
				String publisher = request.getParameter("publisher") ;
				String years = request.getParameter("years") ;
				String revision = request.getParameter("revision") ;
				String exterior = request.getParameter("exterior") ;
				String quantity1 = request.getParameter("quantity") ;
				String other = request.getParameter("other") ;
				String picname = request.getParameter("picname");
				String picurl = request.getParameter("picurl");
				String oldpicurl = request.getParameter("oldpicurl");
				String type = request.getParameter("type");
				String isUpload = request.getParameter("isUpload");
				if("".equals(quantity1) || quantity1==null){
					quantity1 = "0" ;
				}
				int quantity = Integer.parseInt(quantity1) ;	
				
				if(!"".equals(isbn) && ! "".equals(bname) && ! "".equals(author) && ! "".equals(type))
				{	
					Book book = new Book() ;
					book.setBid(Long.parseLong(bid));
					book.setIsbn(isbn) ;
					book.setBname(bname) ;
					book.setAuthor(author) ;
					book.setPublisher(publisher) ;
					book.setYears(years) ;
					book.setRevision(revision) ;
					book.setExterior(exterior) ;
					book.setQuantity(quantity) ;
					book.setPicname(picname) ;
					book.setPicurl(picurl) ;
					book.setOther(other) ;
					book.setType(type);
					try{
						//插入数据库
						tag = Factory.getBookDAOInstance().edit(book) ;
					}
					catch(Exception e){
						response.getWriter().write("{\"success\":false,\"msg\":\"真不好意思，服务器犯错了，换个姿势试一试\"}");
					}
					if(tag){
						if("true".equals(isUpload)){
							if(copyFile(path,path1,picurl)){
								response.getWriter().write("{\"success\":true,\"msg\":\"编辑成功\"}");
							}else{
								response.getWriter().write("{\"success\":true,\"msg\":\"编辑成功，图片上传失败了\"}");
							}
							File file = new File(path1,oldpicurl);
							if(file.exists()){
								file.delete();
							}
						}else{
							response.getWriter().write("{\"success\":true,\"msg\":\"编辑成功\"}");
						}
					}
				}
			}else if(bid!=null && !"".equals(bid)){
				List<Book> all = null;
				try{
					all = Factory.getBookDAOInstance().queryAllBookByBid(bid);
				}catch(Exception ex){}
				if(all.size()>0){
					Book book = (Book)all.get(0);
					request.setAttribute("book", book);
					//跳转
					RequestDispatcher dispatcher = request.getRequestDispatcher("book_edit.jsp");
					dispatcher.forward(request, response) ;
				}	
			}else{
				//跳转
				RequestDispatcher dispatcher = request.getRequestDispatcher("/");
				dispatcher.forward(request, response) ;
			}
		}else{
			//跳转
			RequestDispatcher dispatcher = request.getRequestDispatcher("/login");
			dispatcher.forward(request, response) ;
		}
	}
	
	public boolean copyFile(String path,String path1,String fileUrl){
		boolean tag = false;
		try{
			//复制图片
			int bytesum = 0;
			int byteread = 0;
			File uploadFile = new File(path,fileUrl);
			File newFile = new File(path1,fileUrl);
			if(uploadFile.exists()){
				InputStream inStream = new FileInputStream(uploadFile);
				FileOutputStream fs = new FileOutputStream(newFile);
				byte[] buffer = new byte[ 1444 ];
				while((byteread = inStream.read(buffer)) != -1 ){
					bytesum += byteread; //字节数 文件大小
					fs.write(buffer,0,byteread);
				}
				inStream.close();
				tag  = true;
				uploadFile.delete();
			}
		}catch(Exception ex){
		}
		return tag;
	}
	
}
